#include "iConfig.hpp"

#if GLF_PLATFORM_WIN32

#include <windows.h>
#include <glf/core/syncEvent.h>

namespace glf {

SyncEvent::SyncEvent()
	: m_Initialized(false) {
	Init();
}

SyncEvent::SyncEvent(DeferEvent)
	: m_Initialized(false) {
}

void SyncEvent::Init() {
	GLF_ASSERT(m_Initialized == false);

	m_Event[SIGNAL]  = CreateEvent(NULL, false, false, NULL);
	m_Event[RELEASE] = CreateEvent(NULL, true,  false, NULL);

	m_Initialized = true;
}

SyncEvent::~SyncEvent() {
	if (m_Initialized)
	{
		CloseHandle(m_Event[SIGNAL]);
		CloseHandle(m_Event[RELEASE]);
	}
}

void SyncEvent::Signal() {
	GLF_ASSERT(m_Initialized);

	SetEvent(m_Event[SIGNAL]);
}

void SyncEvent::Set() {
	GLF_ASSERT(m_Initialized);

	SetEvent(m_Event[RELEASE]);
}

void SyncEvent::Reset() {
	GLF_ASSERT(m_Initialized);

	ResetEvent(m_Event[RELEASE]);
}

bool SyncEvent::Wait(unsigned long duration) {
	GLF_ASSERT(m_Initialized);

	duration = duration ? duration : INFINITE;
	return WaitForMultipleObjects(2, m_Event, false, duration) == WAIT_OBJECT_0;
}

} // namespace glf

#endif // GLF_PLATFORM_WIN32
